import cv2
import mediapipe as mp
import time


class FaceDetection():
    def __init__(self,min_detection_confidence=0.5):
        self.min_detection_confidence = min_detection_confidence  #置信度
        self.mpFaceDetection = mp.solutions.face_detection
        self.mpDraw = mp.solutions.drawing_utils
        self.faceDetection = self.mpFaceDetection.FaceDetection(self.min_detection_confidence)


    def findFaces(self,frame,draw=True):
        frameRGB = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        self.results = self.faceDetection.process(frameRGB)
        boxs = []
        if self.results.detections:
            for id, detection in enumerate(self.results.detections):
                # mpDraw.draw_landmarks(frame,detection)
                h, w, c = frame.shape
                boxC = detection.location_data.relative_bounding_box
                box = int(boxC.xmin * w), int(boxC.ymin * h), int(boxC.width * w), int(boxC.height * h)
                boxs.append([id,box,detection.score])
                frame = self.draw(frame,box)
                cv2.putText(frame, f'{int(detection.score[0] * 100)}%', (box[0], box[1] - 20), cv2.FONT_HERSHEY_PLAIN,
                            2, (0, 255, 0), 3)
        return frame,boxs


    def draw(self,frame,box,l=30,t=5,rt=1):
        x,y,w,h = box
        x1,y1 = x+w,y+h
        cv2.rectangle(frame, box, (25, 0, 255), rt)
        # 左上角
        cv2.line(frame, (x, y), (x + l, y), (0, 0, 255), t)
        cv2.line(frame, (x, y), (x, y + l), (0, 0, 255), t)
        # 右上角
        cv2.line(frame, (x1, y), (x1 - l, y), (0, 0, 255), t)
        cv2.line(frame, (x1, y), (x1, y + l), (0, 0, 255), t)
        # 左下角
        cv2.line(frame, (x, y1), (x + l, y1), (0, 0, 255), t)
        cv2.line(frame, (x, y1), (x, y1 - l), (0, 0, 255), t)
        # 右下角
        cv2.line(frame, (x1, y1), (x1 - l,y1), (0, 0, 255), t)
        cv2.line(frame, (x1, y1), (x1, y1 - l), (0, 0, 255), t)
        return frame


def main():
    cap = cv2.VideoCapture(0)
    Ptime = 0
    detector = FaceDetection()
    while True:
        ret, frame = cap.read()
        frame,boxs = detector.findFaces(frame)
        Ctime = time.time()
        fps = 1 / (Ctime - Ptime)
        Ptime = Ctime
        cv2.putText(frame, f'fps:{int(fps)}', (10, 70), cv2.FONT_HERSHEY_PLAIN, 3, (0, 255, 0), 3)
        cv2.imshow('frame', frame)
        if cv2.waitKey(45) == ord('q'):
            break


if __name__ == '__main__':
    main()